<?php

namespace Handler;

use CFPropertyList\CFPropertyList;
use Config\Cfg;
use Extension\ApkParser;
use Extension\Tools;
use GatewayWorker\Lib\Db;
use Workerman\Lib\Timer;
use Extension\ManagerRequest;

class LobbyHandler {
	/**
	 * 单例
	 *
	 * @var LobbyHandler
	 */
	private static $m_Instance;
	/**
	 * 大厅配置信息
	 *
	 * @var array
	 */
	private $m_LobbyInfo;
	/**
	 * 游戏配置信息
	 *
	 * @var array
	 */
	private $m_AppInfo;
	/**
	 * 视频文件信息
	 *
	 * @var array
	 */
	private $m_VideoInfo;
	/**
	 * 距离定时更新所剩余的秒数
	 *
	 * @var int
	 */
	private $m_DayLag;
	/**
	 * 距离月底所剩余的秒数
	 *
	 * @var int
	 */
	private $m_MonthLag;
	private $m_BeginMonth;
	private $m_EndMonth;
	/**
	 * 构造函数
	 */
	protected function __construct() {
		$this->mb_InitLobbyInfo ();
		$this->mb_InitAppInfo ();
		$this->m_DayLag = Tools::mb_GetTimeDifference ( strtotime ( date ( 'Y-m-d', time () ) ) + 86400, Tools::mb_GetCurDateTime () );
		$this->m_MonthLag = Tools::mb_GetTimeDifference ( date ( 'Y-m-01 00:00:00', strtotime ( '+1 month' ) ), Tools::mb_GetCurDateTime () );
		
		// $this->m_BeginMonth = date ( 'Y-m-01 00:00:00', strtotime ( date ( "Y-m-d" ) ) );
		// // echo $this->m_BeginMonth;
		// // echo "\n";
		// $this->m_EndMonth = date ( 'Y-m-d 23:59:50', strtotime ( "$this->m_BeginMonth +1 month -1 day" ) );
		// // echo $this->m_EndMonth;
		// // echo "\n";
		
		Timer::add ( 1, array (
				$this,
				'mb_TimerTask' 
		), array (), true );
	}
	/**
	 * 析构函数
	 */
	protected function __destruct() {
	}
	/**
	 * 获取单例
	 *
	 * @return \Handler\LobbyHandler
	 */
	public static function mb_GetInstance() {
		if (! (self::$m_Instance instanceof self)) {
			self::$m_Instance = new self ();
		}
		return self::$m_Instance;
	}
	/**
	 * 初始化大厅配置信息
	 */
	public function mb_InitLobbyInfo() {
		$tpData = TPHandler::mb_GetInstance ()->mb_GetLobbyInfoToTP ();
		if ($tpData->state) {
			$lobbyData = json_decode ( $tpData->data );
		} else {
			Tools::mb_LogResult ( "外部服务器异常，无法请求到大厅信息" );
		}
		
		$this->m_LobbyInfo = Db::instance ( 'lobby' )->select ( '*' )->from ( 'lobbyinfo' )->query ();
		for($i = 0; $i < count ( $this->m_LobbyInfo ); $i ++) {
			$this->m_LobbyInfo [$i] ['downhelp'] = Cfg::HOST_NAME . $this->m_LobbyInfo [$i] ['downhelp'];
			$this->m_LobbyInfo [$i] ['sw_regist'] = $lobbyData->sw_regist;
			$this->m_LobbyInfo [$i] ['sw_login'] = $lobbyData->sw_login;
			$this->m_LobbyInfo [$i] ['sw_phone'] = $lobbyData->sw_phone;
			
			$this->m_LobbyInfo [$i] ['bulletin'] = $lobbyData->bulletin;
			$this->m_LobbyInfo [$i] ['broadcast'] = $lobbyData->broadcast;
			$this->m_LobbyInfo [$i] ['recharge'] = $lobbyData->recharge;
			$this->m_LobbyInfo [$i] ['status'] = ( int ) $lobbyData->status;
		}
	}
	/**
	 * 初始化游戏配置信息
	 */
	public function mb_InitAppInfo() {
		$tpData = TPHandler::mb_GetInstance ()->mb_GetGameInfoToTP ();
		if ($tpData->state) {
			$gameData = json_decode ( $tpData->data );
		} else {
			Tools::mb_LogResult ( "外部服务器异常，无法请求到大厅信息" );
		}
		$this->m_AppInfo = Db::instance ( 'lobby' )->select ( '*' )->from ( 'appinfo' )->orderByASC ( array (
				'rank' 
		) )->where ( "status != '2'" )->query ();
		$url = Cfg::HOST_NAME . 'LobbyFile/';
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			$id = $this->m_AppInfo [$i] ['id'];
			$this->m_AppInfo [$i] ['android_assetbundle'] = $url . $id . '/' . $this->m_AppInfo [$i] ['android_assetbundle'];
			$this->m_AppInfo [$i] ['ios_assetbundle'] = $url . $id . '/' . $this->m_AppInfo [$i] ['ios_assetbundle'];
			$this->m_AppInfo [$i] ['pc_assetbundle'] = $url . $id . '/' . $this->m_AppInfo [$i] ['pc_assetbundle'];
			$this->m_AppInfo [$i] ['ico'] = $url . $id . '/' . $this->m_AppInfo [$i] ['ico'];
			$this->m_AppInfo [$i] ['loadingscreen'] = $url . $id . '/' . $this->m_AppInfo [$i] ['loadingscreen'];
			$this->m_AppInfo [$i] ['loadingframe'] = $url . $id . '/' . $this->m_AppInfo [$i] ['loadingframe'];
			$this->m_AppInfo [$i] ['loadingbar'] = $url . $id . '/' . $this->m_AppInfo [$i] ['loadingbar'];
			$this->m_AppInfo [$i] ['onlineusers'] = array ();
			
			for($j = 0; $j < count ( $gameData ); $j ++) {
				if ($gameData [$j]->id == $id) {
					$this->m_AppInfo [$i] ['status'] = ( int ) $gameData [$j]->status;
					$this->m_AppInfo [$i] ['coinvalue'] = ( int ) $gameData [$j]->coinvalue;
					$this->m_AppInfo [$i] ['level'] = ( int ) $gameData [$j]->level;
				}
			}
		}
	}
	/**
	 * 初始化视频文件信息
	 */
	public function mb_InitVideoFiles() {
		$videoFiles = $this->mb_ScanFiles ( Cfg::VIDEO_DIR );
		
		if (is_array ( $videoFiles ) == false)
			return;
		
		$videoDatas = array ();
		$url = Cfg::HOST_NAME . 'VideoFile/';
		for($i = 0; $i < count ( $videoFiles ); $i ++) {
			$video = $videoFiles [$i];
			$video = str_replace ( Cfg::VIDEO_DIR . '/', '', $video );
			$fileUrl = $url . $video;
			
			$dirUrl = '';
			$dirs = explode ( '/', $video );
			for($j = 0; $j < count ( $dirs ) - 1; $j ++) {
				if ($j == count ( $dirs ) - 2) {
					$dirUrl = $dirUrl . $dirs [$j];
				} else {
					$dirUrl = $dirUrl . $dirs [$j] . '/';
				}
			}
			
			$fileName = $dirs [count ( $dirs ) - 1];
			$videoDatas [] = array (
					'fileurl' => $fileUrl,
					'dirurl' => $dirUrl,
					'filename' => $fileName 
			);
		}
		$this->m_VideoInfo = $videoDatas;
	}
	/**
	 * 获取大厅配置信息
	 *
	 * @param unknown $id        	
	 * @return NULL
	 */
	public function mb_GetLobbyInfo($id) {
		if ($this->m_LobbyInfo != null) {
			for($i = 0; $i < count ( $this->m_LobbyInfo ); $i ++) {
				if ($this->m_LobbyInfo [$i] ['id'] == $id)
					return $this->m_LobbyInfo [$i];
			}
		} else {
			return null;
		}
	}
	/**
	 * 获取所有游戏配置信息
	 *
	 * @return array
	 */
	public function mb_GetAppInfo() {
		return $this->m_AppInfo;
	}
	/**
	 * 获取游戏配置信息
	 *
	 * @param unknown $id        	
	 * @return mixed|NULL
	 */
	public function mb_GetAppInfoForId($id) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $id)
				return $this->m_AppInfo [$i];
		}
		return null;
	}
	/**
	 * 获取游戏配置信息
	 *
	 * @param unknown $scene        	
	 * @return mixed|NULL
	 */
	public function mb_GetAppInfoForScene($scene) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['scene'] == $scene)
				return $this->m_AppInfo [$i];
		}
		return null;
	}
	public function mb_SetAppInfoForId($id, $appInfo) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $id) {
				Db::instance ( 'lobby' )->update ( 'appinfo' )->cols ( array (
						'android_ver' => $appInfo ['android_ver'],
						'ios_ver' => $appInfo ['ios_ver'],
						'pc_ver' => $appInfo ['pc_ver'] 
				) )->where ( "id = '$id'" )->query ();
				$this->m_AppInfo [$i] = $appInfo;
				return true;
			}
		}
		return false;
	}
	/**
	 * 更改游戏状态
	 *
	 * @param unknown $appId        	
	 * @param unknown $status        	
	 * @return boolean
	 */
	public function mb_ChangeAppStatus($appId, $status) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $appId) {
				Db::instance ( 'lobby' )->update ( 'appinfo' )->cols ( array (
						'status' => $status 
				) )->where ( "id = '$appId'" )->query ();
				$this->m_AppInfo [$i] ['status'] = ( int ) $status;
				return true;
			}
		}
		return false;
	}
	public function mb_ChangeAppCoinValue($appId, $coinValue) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $appId) {
				$this->m_AppInfo [$i] ['coinvalue'] = ( int ) $coinValue;
				return true;
			}
		}
		return false;
	}
	public function mb_ChangeAppLevel($appId, $level) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $appId) {
				$this->m_AppInfo [$i] ['level'] = ( int ) $level;
				return true;
			}
		}
		return false;
	}
	/**
	 * 获取所有视频信息
	 *
	 * @return array
	 */
	public function mb_GetVideoInfo() {
		return $this->m_VideoInfo;
	}
	/**
	 * 更新apk包信息
	 */
	public function mb_UpdateApkInfo() {
		$apkParser = new ApkParser ();
		$apkPath = Cfg::APK_PATH;
		
		$result = $apkParser->open ( $apkPath );
		$ver = $apkParser->getVersionName ();
		$md5 = md5_file ( $apkPath );
		
		Db::instance ( 'lobby' )->update ( 'lobbyinfo' )->cols ( array (
				'md5' => $md5,
				'ver' => $ver,
				'updatedate' => Tools::mb_GetCurDateTime () 
		) )->where ( "id='1'" )->query ();
		$this->m_LobbyInfo [0] ['ver'] = $ver;
		$this->m_LobbyInfo [0] ['md5'] = $md5;
	}
	/**
	 * 更新ipa包信息
	 */
	public function mb_UpdateIpaInfo() {
		$ipaPath = Cfg::IPA_PATH;
		$zip = new \ZipArchive ();
		if ($zip->open ( $ipaPath ) === TRUE) {
			$content = $zip->getFromName ( 'Payload/lobby.app/Info.plist' );
			$zip->close ();
			
			$plist = new CFPropertyList ();
			$plist->parse ( $content );
			// 获取版本号
			$ver = $plist->toArray () ['CFBundleShortVersionString'];
			$md5 = md5_file ( $ipaPath );
			Db::instance ( 'lobby' )->update ( 'lobbyinfo' )->cols ( array (
					'md5' => $md5,
					'ver' => $ver,
					'updatedate' => Tools::mb_GetCurDateTime () 
			) )->where ( "id='2'" )->query ();
			$this->m_LobbyInfo [1] ['ver'] = $ver;
		}
	}
	/**
	 * 设置大厅状态
	 *
	 * @param unknown $status
	 *        	状态（0：营运中，1：维护中，2：暂停营运）
	 */
	public function mb_SetLobbyStatus($status) {
		Db::instance ( 'lobby' )->update ( 'lobbyinfo' )->cols ( array (
				'status' => $status 
		) )->query ();
		for($i = 0; $i < count ( $this->m_LobbyInfo ); $i ++) {
			$this->m_LobbyInfo [$i] ['status'] = $status;
		}
	}
	/**
	 * 扫描目录下的文件以及子文件夹
	 *
	 * @param unknown $dir        	
	 * @return array|unknown
	 */
	private function mb_ScanFiles($dir) {
		if (is_dir ( $dir )) {
			$files = array ();
			$childDirs = scandir ( $dir );
			foreach ( $childDirs as $childDir ) {
				if ($childDir == '.' || $childDir == '..')
					continue;
				
				if (is_dir ( $dir . '/' . $childDir )) {
					$files = array_merge ( $files, $this->mb_ScanFiles ( $dir . '/' . $childDir ) );
				} else {
					$files [] = $dir . '/' . $childDir;
				}
			}
			return $files;
		} else {
			return $dir;
		}
	}
	/**
	 * 时间任务(每一秒执行一次)
	 */
	public function mb_TimerTask() {
		// 每日凌晨0时更新
		if (-- $this->m_DayLag == 0) {
			$this->m_DayLag = 86400;
		}
		// 每月1号零时执行
		if (-- $this->m_MonthLag == 0) {
			$begin = date ( 'Y-m-01 00:00:00', strtotime ( '-1 month' ) );
			$end = date ( 'Y-m-t 23:59:59', strtotime ( '-1 month' ) );
			
			$logs = array ();
			$logData = Db::instance ( 'manager' )->select ( 'username,coins,type,code' )->from ( 'userrechargelog' )->where ( "date>'$begin' AND date<'$end'" )->query ();
			for($i = 0; $i < count ( $logData ); $i ++) {
				$name = $logData [$i] ['username'];
				$coin = $logData [$i] ['coins'];
				$type = $logData [$i] ['type'];
				$code = $logData [$i] ['code'];
				
				$data = array (
						0,
						0,
						0
				);
				$data [$type] += $coin;
				
				if (isset ( $logs[$name] )) {
					$logs[$name] ['up'] += $data [0];
					$logs[$name] ['down'] += $data [1];
					$logs[$name] ['send'] += $data [2];
					
					
				} else {
					$logs [$name] = array (
							'name' => $name,
							'code' => $code,
							'up' => $data [0],
							'down' => $data [1],
							'send' => $data [2]
					);
				}
			}
			
			foreach ( $logs as $item ) {
				$name = $item ['name'];
				$code = $item ['code'];
				$up = $item ['up'];
				$down = $item ['down'];
				$send = $item ['send'];
				$coins = Db::instance ( 'manager' )->select ( 'coin' )->from ( 'userinfo' )->where ( "name='$name'" )->row () ['coin'];
				Db::instance ( 'manager' )->query ( "INSERT INTO `userstatisticdata` (`name`, `code`, `up`, `down`, `send`, `coins`) VALUES ('$name', '$code', '$up', '$down', '$send', '$coins') ON DUPLICATE KEY UPDATE up='$up', down='$down', send='$send', coins='$coins';" );
			}
			
			$this->m_MonthLag = Tools::mb_GetTimeDifference ( date ( 'Y-m-01 00:00:00', strtotime ( '+1 month' ) ), Tools::mb_GetCurDateTime () );
		}
	}
	public function mb_TestMonth() {
		$begin = date ( 'Y-m-01 00:00:00', strtotime ( date ( "Y-m-d" ) ) );
		$end = date ( 'Y-m-d 23:59:59', strtotime ( "$begin +1 month -1 day" ) );
		
		$logs = array ();
		$logData = Db::instance ( 'manager' )->select ( 'username,coins,type,code' )->from ( 'userrechargelog' )->where ( "date>'$begin' AND date<'$end'" )->query ();
		for($i = 0; $i < count ( $logData ); $i ++) {
			$name = $logData [$i] ['username'];
			$coin = $logData [$i] ['coins'];
			$type = $logData [$i] ['type'];
			$code = $logData [$i] ['code'];
			
			$data = array (
					0,
					0,
					0 
			);
			$data [$type] += $coin;
			
			if (isset ( $logs[$name] )) {
				$logs[$name] ['up'] += $data [0];
				$logs[$name] ['down'] += $data [1];
				$logs[$name] ['send'] += $data [2];
				
				
			} else {
				$logs [$name] = array (
						'name' => $name,
						'code' => $code,
						'up' => $data [0],
						'down' => $data [1],
						'send' => $data [2] 
				);
			}
		}
		
		foreach ( $logs as $item ) {
			$name = $item ['name'];
			$code = $item ['code'];
			$up = $item ['up'];
			$down = $item ['down'];
			$send = $item ['send'];
			$coins = Db::instance ( 'manager' )->select ( 'coin' )->from ( 'userinfo' )->where ( "name='$name'" )->row () ['coin'];
			Db::instance ( 'manager' )->query ( "INSERT INTO `userstatisticdata` (`name`, `code`, `up`, `down`, `send`, `coins`) VALUES ('$name', '$code', '$up', '$down', '$send', '$coins') ON DUPLICATE KEY UPDATE up='$up', down='$down', send='$send', coins='$coins';" );
		}
	}
	
	/**
	 * 统计在线玩家
	 *
	 * @param string $game
	 *        	场景名
	 * @param bool $isAdd
	 *        	true 增加， false 减少
	 */
	public function mb_StatisticsOnlineUsers($gameId, $name, $isAdd) {
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $gameId) {
				if ($isAdd) {
					// 添加
					$this->m_AppInfo [$i] ['onlineusers'] [] = $name;
					break;
				} else {
					// 移除
					for($j = 0; $j < count ( $this->m_AppInfo [$i] ['onlineusers'] ); $j ++) {
						if ($this->m_AppInfo [$i] ['onlineusers'] [$j] == $name) {
							array_splice ( $this->m_AppInfo [$i] ['onlineusers'], $j, 1 );
							return;
						}
					}
				}
			}
		}
	}
	
	/**
	 * 获取各个游戏在线用户
	 *
	 * @return NULL[][]
	 */
	public function mb_GetGameOnLineUsers() {
		$retData = array ();
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			$retData [] = array (
					'id' => $this->m_AppInfo [$i] ['id'],
					'name' => $this->m_AppInfo [$i] ['name'],
					'online' => ( string ) count ( $this->m_AppInfo [$i] ['onlineusers'] ) 
			);
		}
		return $retData;
	}
	/**
	 * 获取某个游戏详细在线人数
	 *
	 * @param unknown $id        	
	 * @return string
	 */
	public function mb_GetGameOnLineUserForGameId($gameId) {
		$retData = array ();
		for($i = 0; $i < count ( $this->m_AppInfo ); $i ++) {
			if ($this->m_AppInfo [$i] ['id'] == $gameId) {
				return $this->m_AppInfo [$i] ['onlineusers'];
			}
		}
		return json_encode ( array () );
	}
	/**
	 * 更新大厅信息
	 *
	 * @param unknown $key        	
	 * @param unknown $value        	
	 */
	public function mb_UpdateLobbyInfo($key, $value) {
		for($i = 0; $i < count ( $this->m_LobbyInfo ); $i ++) {
			$this->m_LobbyInfo [$i] ["$key"] = $value;
		}
		
		print_r ( $this->m_LobbyInfo [0] );
	}
	/**
	 * 设置广播信息
	 *
	 * @param unknown $msg        	
	 */
	public function mb_SetDefaultBroadcast($msg) {
		for($i = 0; $i < count ( $this->m_LobbyInfo ); $i ++) {
			$this->m_LobbyInfo [$i] ['broadcast'] = $msg;
		}
		Db::instance ( 'lobby' )->update ( 'lobbyinfo' )->cols ( array (
				'broadcast' => $msg 
		) )->query ();
	}
	/**
	 * 获取一个闲置账号
	 *
	 * @return number
	 */
	public function mb_GetIdleName() {
		$isGet = false;
		while ( ! $isGet ) {
			$name = mt_rand ( 100000, 999999 );
			if (Db::instance ( 'lobby' )->select ( '*' )->from ( 'userinfo' )->where ( "name='$name'" )->row () == null) {
				$isGet = true;
			}
		}
		return $name;
	}
	public function mb_Test() {
		$reqSFS = new ManagerRequest ();
		$json = json_decode ( $reqSFS->mb_TestConnect () );
		$result = $json->m_Result;
		$data = $json->m_Data;
		$sign = $json->m_Sign;
		
		if (md5 ( $result . $data . Cfg::MSG_MD5 ) == $sign) {
			echo "1231321332";
		} else {
			echo "jfkdlsjfldsj";
		}
	}
}